<?php

namespace Biz\service\wiki;

use Biz\cache\PhotoRelaBaseGoods;
use Biz\cache\PhotoRelaGoods;
use Biz\cache\wiki\GoodsHot;
use Biz\cache\wiki\ObjRelateWiki as cObjRelateWiki;
use Biz\cache\wiki\TopicWiki as cTopicWiki;
use Biz\cache\wiki\WikiBasicCounter;
use Biz\model\wiki\ObjRelateWiki as mObjRelateWiki;
use Biz\model\wiki\Wiki as mWiki;
use Biz\module\Classes\wiki\RelateWiki as clsRelateWiki;
use Biz\module\Classes\wiki\TopicWiki;
use Biz\module\Classes\wiki\Wiki as clsWiki;
use Biz\pockets\serviceTrait\_Async;
use Biz\service\Goods;
use Biz\service\wiki\Wiki as sWiki;
use Doraemon\cache\Photos as cPhotos;
use Doraemon\cache\TopicCounter;
use Doraemon\model\Es\MainContent;
use Doraemon\model\Photos as mPhotos;
use Doraemon\model\TopicActivity;
use Doraemon\model\TopicRelation as mTopicRelation;
use Doraemon\module\Packages\TagFormat\Module\ShowTagFormat;
use Doraemon\service\Article as sArticle;
use Doraemon\service\Elasticsearch\Photo as esPhotoService;
use Doraemon\service\es\EsObjRelateWikiSupplement;
use Doraemon\service\Guide as sGuide;
use Doraemon\service\Photos as sPhotos;
use Doraemon\service\statSign\Basic as basicStatSign;
use Doraemon\service\statSign\StatSignFormat;
use Doraemon\tools\BlockType;
use Doraemon\tools\IdParse;
use Doraemon\tools\Log;
use Doraemon\model\Topic\TopicActivity as TopicActivityModel;


class ObjRelateWiki
{
    use _Async;

    const USER_COMMENT = 0; //住友说
    const BRAND_COMMENT = 1; //品牌说
    const STORE_COMMENT = 2; //门店说

    /**
     * 获取已关联的wiki列表
     * @param $objId
     * @param $objType 1:note 2:文章 3：整屋
     * @param array $imgIds
     * @param int $uid
     * @return array
     */
    public static function getRelateWikiList($objId, $objType, $imgIds = [], $uid = 0)
    {
        //内容详情wiki弹出的抽屉列表使用grpc
        $result = [];
        if (empty($imgIds)) {
            $wikiGrpcClient = \Wiki\GrpcClient::getInstance();
            $aRet = $wikiGrpcClient->getRelatedWikiListByObjId([
                "objId" => $objId,
                "objType" => $objType,
                "uid" => $uid,
                "fieldsGroup" => Wiki::FIELDS_GROUP_LIST
            ]);
            if ($aRet['biz_code'] != 0) {
                return [];
            }
            if (isset($aRet['result']['list'][$objId]['wiki_list']) && !empty($aRet['result']['list'][$objId]['wiki_list'])) {
                $result = $aRet['result']['list'][$objId]['wiki_list'];
            }
        } else {
            $imgIds = array_unique($imgIds);
            $wikiGrpcClient = \Wiki\GrpcClient::getInstance();
            $aRet = $wikiGrpcClient->getRelatedWikiListByRelObjIds([
                "objId" => $objId,
                "objType" => $objType,
                "relObjIds" => $imgIds,
                "relObjType" => mObjRelateWiki::REL_OBJ_TYPE_PIC,
                "fieldsGroup" => Wiki::FIELDS_GROUP_LIST,
                "uid" => $uid,
            ]);
            if ($aRet['biz_code'] != 0) {
                return [];
            }
            if (isset($aRet['result']['list']) && !empty($aRet['result']['list'])) {
                $res = $aRet['result']['list'];
                foreach ($imgIds as $imgId) {
                    $wikiList = $res[$imgId]['wiki_list'] ?? [];
                    if ($wikiList) {
                        $result = array_merge($result, $wikiList);
                    }
                }
            }
        }
        return ['list' => $result];
    }

    public static function formatRelatedWikiStatSign($relatedId, $wikiList, array $statSignParams = [])
    {
        $statSignParams['relate_id'] = $relatedId;
        $wikiStatSign = basicStatSign::genStatSign(
            basicStatSign::MODULE_CONTENT_DETAIL_GOODS_LIST_WIKI_CARD,
            [
                basicStatSign::EXTEND_KEY_RELATE_OBJ_TYPE => IdParse::getType($relatedId),
                basicStatSign::EXTEND_KEY_RELATE_OBJ_ID => $relatedId,
            ],
            $statSignParams, false);
        $result = StatSignFormat::formatWikiListData($wikiList, $wikiStatSign);
        return $result;
    }

    /**
     * 根据obj id获取已经关联的wiki信息
     * @param array $objIds
     * @param $objType 1:note 2:文章 3：整屋
     * @param bool $sortPic 是否按照pic顺序排序
     * @param int $uid
     * @return array
     */
    public static function getWikiListByObjIds(array $objIds, $objType, $sortPic = true, $uid = 0)
    {
        $result = [];
        $wikiGrpcClient = \Wiki\GrpcClient::getInstance();
        $aRet = $wikiGrpcClient->getRelatedWikiListByObjIds([
            "objIds" => $objIds,
            "objType" => $objType,
            "fieldsGroup" => Wiki::FIELDS_GROUP_LIST,
            "uid" => $uid
        ]);
        if ($aRet['biz_code'] != 0) {
            return [];
        }
        $res = $aRet['result']['list'] ?? [];
        foreach ($res as $noteId => $row) {
            $result[$noteId]['list'] = $row['wiki_list'];
        }
        return $result;
    }

    /**
     * 获取关联列表的基础方法
     * @param $objType
     * @param array $objIds
     * @return array
     */
    public static function getRelateListByObjIds($objType, array $objIds)
    {
        list($cacheData, $noCacheKeys) = cObjRelateWiki::getObjCaches($objType, $objIds);
        if ($noCacheKeys) {
            $where = [
                'obj_id' => $noCacheKeys,
                'obj_type' => $objType,
                'status' => mObjRelateWiki::STATUS_NORMAL,
            ];
            $res = mObjRelateWiki::getByWhere($where);
            $relateList = [];
            foreach ($res as $row) {
                $relateList[$row['obj_id']][] = $row;
            }
            if ($relateList) {
                cObjRelateWiki::setObjCaches($objType, $relateList);
            }
            $relList = $cacheData + $relateList;
        } else {

            $relList = $cacheData;
        }
        //排序x
        $list = [];
        if ($relList) {
            foreach ($relList as $noteId => $noteList) {
                foreach ($noteList as $row) {
                    $list[] = $row;
                }
            }
            foreach ($list as $key => $row) {
                $relObjType[$key] = $row['rel_obj_type'];
                $addtime[$key] = $row['addtime'];
            }
            array_multisort($relObjType, SORT_ASC, $addtime, SORT_DESC, $list);
        }
        $result = [];
        foreach ($list as $row) {
            $result[$row['obj_id']][] = $row;
        }
        return $result;
    }

    /**
     * 查询整屋详情关联的wiki
     * @param $articleId
     * @return array
     */
    public static function getRelWikiForArticleDetail($articleId)
    {
        $result = [];
        $objIds[] = $articleId;
        $noteIds = sArticle::getRelaNoteIds($articleId);//整屋下所有的note
        $objIds = array_merge($objIds, $noteIds);
        $where = [
            'obj_id' => $objIds,
            'obj_type' => [mObjRelateWiki::OBJ_TYPE_ARTICLE, mObjRelateWiki::OBJ_TYPE_NOTE],
            'status' => mObjRelateWiki::STATUS_NORMAL,
        ];
        $res = mObjRelateWiki::getByWhere($where);
        $wikiIds = array_column($res, 'wiki_id');
        $wikiIds = array_unique(array_filter($wikiIds));
        $wikiList = clsWiki::getWikiBaseInfos($wikiIds);
        $noteRelWikiIds = [];//note关联的wiki
        $articleImgRelWikiIds = [];//整屋的图片关联的wiki
        foreach ($res as $row) {
            if ($row['rel_obj_type'] != mObjRelateWiki::REL_OBJ_TYPE_COMMENT) {
                switch ($row['obj_type']) {
                    case mObjRelateWiki::OBJ_TYPE_ARTICLE:
                        if ($row['rel_obj_type'] == mObjRelateWiki::REL_OBJ_TYPE_PIC && $row['rel_obj_id']) {
                            if (!isset($articleImgRelWikiIds[$row['rel_obj_id']])) {
                                $articleImgRelWikiIds[$row['rel_obj_id']] = [];
                            }
                            if (!in_array($row['wiki_id'], $articleImgRelWikiIds[$row['rel_obj_id']])) {
                                $articleImgRelWikiIds[$row['rel_obj_id']][] = $row['wiki_id'];
                            }
                        }
                        break;
                    case  mObjRelateWiki::OBJ_TYPE_NOTE:
                        if (!isset($noteRelWikiIds[$row['obj_id']])) {
                            $noteRelWikiIds[$row['obj_id']] = [];
                        }
                        if (!in_array($row['wiki_id'], $noteRelWikiIds[$row['obj_id']])) {
                            $noteRelWikiIds[$row['obj_id']][] = $row['wiki_id'];
                        }
                        break;
                }
            }
        }
        foreach ($noteRelWikiIds as $noteId => $wikiIds) {
            $wikiImgs = [];
            $wikiNum = 0;
            foreach ($wikiIds as $wikiId) {
                if (isset($wikiList[$wikiId])) {
                    $wikiImgs[] = $wikiList[$wikiId]['cover_img'];
                    $wikiNum++;
                }
            }
            $result[] = [
                'obj_id' => $noteId,
                'obj_type' => BlockType::TYPE_PHOTO,
                'wiki_num' => $wikiNum,
                'wiki_imgs' => array_filter($wikiImgs),
            ];
        }

        foreach ($articleImgRelWikiIds as $picId => $wikiIds) {
            $wikiImgs = [];
            $wikiNum = 0;
            foreach ($wikiIds as $wikiId) {
                if (isset($wikiList[$wikiId])) {
                    $wikiImgs[] = $wikiList[$wikiId]['cover_img'];
                    $wikiNum++;
                }
            }
            $result[] = [
                'obj_id' => $articleId,
                'obj_type' => BlockType::TYPE_ARTICLE,
                'pic_id' => $picId,
                'wiki_num' => $wikiNum,
                'wiki_imgs' => array_filter($wikiImgs),
            ];
        }
        return $result;
    }


    /**
     * 通过uid获取关联的内容
     * @param array $uid
     * @param $page
     * @param int $pageSize
     * @return array
     */
    public static function getObjListByUid(array $uid, $page, $pageSize = 20)
    {
        $page = $page ? $page : 1;
        $limit = [$pageSize * ($page - 1), $pageSize];
        $list = mObjRelateWiki::getObjIdsByUids($uid, $limit);
        $count = mObjRelateWiki::getObjIdsCountByUids($uid);
        $isOver = ($page * $pageSize >= $count) ? 1 : 0;
        return ['list' => $list, 'is_over' => $isOver];
    }

    /**
     * note关联wiki
     * @param $uid
     * @param $objId noteId
     * @param array $wikiIds
     * @param string $relObjId （note图片id）
     * @param int $relObjType
     * @param int $type
     * @return array
     * @throws \Exception
     */
    public static function noteRelateWiki(
        $uid,
        $objId,
        array $wikiIds,
        $relObjId = '',
        $relObjType = mObjRelateWiki::REL_OBJ_TYPE_PIC,
        $type = mObjRelateWiki::TYPE_USER_TAG
    )
    {
        try {
            if (!$uid || !$objId) {
                throw new \Exception('参数错误');
            }
            $relObjType = $relObjId ? $relObjType : 0;
            return clsRelateWiki::objRelateWiki($uid, $objId, mObjRelateWiki::OBJ_TYPE_NOTE, $relObjId, $relObjType,
                $wikiIds, $type);
        } catch (Exception $e) {
            Log::wiki_relateNote_warning('note关联wiki失败#data:' . json_encode([
                    'note_id' => $objId,
                    'rel_obj_id' => $relObjId,
                    'rel_obj_type' => $relObjType,
                    'wiki_ids' => $wikiIds,
                    'uid' => $uid,
                    'type' => $type
                ]));
            throw $e;
        }
    }


    /**
     * 整屋关联wiki
     * @param $uid
     * @param $objId string 整屋id
     * @param array $wikiIds
     * @param string $relObjId （整屋的图片id）
     * @param int $relObjType
     * @param int $type
     * @return array
     * @throws \Exception
     */
    public static function articleRelateWiki(
        $uid,
        $objId,
        array $wikiIds,
        $relObjId,
        $relObjType = mObjRelateWiki::REL_OBJ_TYPE_PIC,
        $type = mObjRelateWiki::TYPE_USER_TAG
    )
    {
        try {
            if (!$uid || !$objId) {
                throw new \Exception('参数错误');
            }
            $relObjType = $relObjId ? $relObjType : 0;
            return clsRelateWiki::objRelateWiki($uid, $objId, mObjRelateWiki::OBJ_TYPE_ARTICLE, $relObjId, $relObjType,
                $wikiIds, $type);
        } catch (\Exception $e) {
            Log::wiki_relateNote_warning('整屋关联wiki失败#data:' . json_encode([
                    'article_id' => $objId,
                    'rel_obj_id' => $relObjId,
                    'rel_obj_type' => $relObjType,
                    'wiki_ids' => $wikiIds,
                    'uid' => $uid,
                    'type' => $type
                ]));
            throw $e;
        }
    }

    /**
     * 文章关联wiki
     * @param $uid
     * @param $objId 文章id
     * @param array $wikiIds
     * @param int $type
     * @return mixed
     * @throws \Exception
     */
    public static function blankRelateWiki($uid, $objId, array $wikiIds, $type = mObjRelateWiki::TYPE_USER_REL)
    {
        try {
            if (!$uid || !$objId) {
                throw new \Exception('参数错误');
            }
            return clsRelateWiki::objRelateWiki($uid, $objId, mObjRelateWiki::OBJ_TYPE_BLANK, '', 0, $wikiIds, $type);
        } catch (\Exception $e) {
            Log::wiki_relateBlank_warning('用户' . $uid . '#文章#' . $objId . '关联wiki失败#data:' . json_encode([
                    'obj_id' => $objId,
                    'wiki_ids' => $wikiIds,
                    'uid' => $uid,
                    'type' => $type
                ]));
            throw $e;
        }
    }

    /**
     * 指南关联wiki
     * @param $uid
     * @param $objId 指南id
     * @param array $wikiIds
     * @param int $type
     * @return mixed
     * @throws \Exception
     */
    public static function guideRelateWiki($uid, $objId, array $wikiIds, $type = mObjRelateWiki::TYPE_USER_REL)
    {
        try {
            if (!$uid || !$objId) {
                throw new \Exception('参数错误');
            }
            return clsRelateWiki::objRelateWiki($uid, $objId, mObjRelateWiki::OBJ_TYPE_GUIDE, '', 0, $wikiIds, $type);
        } catch (\Exception $e) {
            Log::wiki_relateBlank_warning('用户' . $uid . '#指南#' . $objId . '关联wiki失败#data:' . json_encode([
                    'obj_id' => $objId,
                    'wiki_ids' => $wikiIds,
                    'uid' => $uid,
                    'type' => $type
                ]));
            throw $e;
        }
    }

    /**
     *
     * 评论关联wiki
     * @param $uid 评论内容主的uid
     * @param $objId 评论的内容id
     * @param $objType 评论的内容类型 1:note 2:文章 3:整屋 4:指南
     * @param $commentId 评论id
     * @param $linkContent 带链接的评论内容
     * @return mixed
     * @throws \Exception
     */
    public static function commentRelateWiki($uid, $objId, $objType, $commentId, $linkContent)
    {
        Log::wiki_relateComment_info('用户' . $uid . '#发评论#' . $commentId . '生存并关联wiki#data:' . json_encode([
                'obj_id' => $objId,
                'obj_type' => $objType,
                'comment_id' => $commentId,
                'content' => $linkContent,
                'uid' => $uid
            ]));
        $wikiId = 0;
        try {
            if ($uid && $objId && $objType && $commentId && $linkContent) {
                $wikiInfo = clsWiki::getWikiByContent($linkContent, $objType, $objId);
                if ($wikiInfo) {
                    $wikiId = $wikiInfo['id'];
                    //评论关联wiki
                    clsRelateWiki::objRelateWiki($uid, $objId, $objType, $commentId,
                        mObjRelateWiki::REL_OBJ_TYPE_COMMENT, [$wikiId]);
                    //更改commentLink resId
                    clsWiki::updateCommentLinkResId($wikiInfo, $objId, $commentId, $uid);
                } else {//解析失败
                    throw new \Exception('url解析失败');
                }
            }
        } catch (\Exception $e) {
            Log::wiki_relateComment_warning('用户' . $uid . '#评论#' . $commentId . '关联wiki失败#data:' . json_encode([
                    'obj_id' => $objId,
                    'obj_type' => $objType,
                    'comment_id' => $commentId,
                    'content' => $linkContent,
                    'wiki_id' => $wikiId,
                    'uid' => $uid,
                    'err_msg' => $e->getMessage()
                ]));
        }
    }

    /**
     * 删除note关联
     * @param $uid
     * @param $noteId
     * @param array $picIds 如果是删除整个note不用传picId
     * @throws \Exception
     */
    public static function delNoteRelate($uid, $noteId, array $picIds = [])
    {
        if ($picIds) {
            clsRelateWiki::delRelateWiki($uid, $noteId, mObjRelateWiki::OBJ_TYPE_NOTE, $picIds,
                mObjRelateWiki::REL_OBJ_TYPE_PIC);
        } else {//删除整个note，需要删除note下所有关联，包含运营添加，评论
            clsRelateWiki::delRelateWiki($uid, $noteId, mObjRelateWiki::OBJ_TYPE_NOTE);
        }
    }

    /**
     * 删除note下所有图片下关联的wiki
     * @param $uid
     * @param $noteId
     * @throws \Exception
     */
    public static function delNoteImgTagRelate($uid, $noteId)
    {
        if ($uid && $noteId) {
            clsRelateWiki::delRelateWiki($uid, $noteId, mObjRelateWiki::OBJ_TYPE_NOTE, null, null, null,
                mObjRelateWiki::TYPE_USER_TAG);
        }
    }

    /**
     * 删除文章关联
     * @param $uid
     * @param $blankId 文章id
     * @throws \Exception
     */
    public static function delBlankRelate($uid, $blankId)
    {
        //需要删除文章下所有关联，包含运营添加，评论
        clsRelateWiki::delRelateWiki($uid, $blankId, mObjRelateWiki::OBJ_TYPE_BLANK);
    }

    /**
     * 删除整屋关联
     * @param $uid
     * @param $articleId
     * @throws \Exception
     */
    public static function delArticleRelate($uid, $articleId)
    {
        //需要删除整屋下所有关联，包含运营添加，评论
        clsRelateWiki::delRelateWiki($uid, $articleId, mObjRelateWiki::OBJ_TYPE_ARTICLE);
    }

    /**
     * 删除指南关联
     * @param $uid
     * @param $guideId
     * @throws \Exception
     */
    public static function delGuideRelate($uid, $guideId)
    {
        //需要指南下所有关联，包含运营添加，评论
        clsRelateWiki::delRelateWiki($uid, $guideId, mObjRelateWiki::OBJ_TYPE_GUIDE);
    }

    /**
     * 删除评论关联
     * @param $uid
     * @param $objId 评论内容id
     * @param $objType 评论内容类型（1：note 2：文章 3：整屋）
     * @param $commentId 评论id
     * @throws \Exception
     */
    public static function delCommentRelate($uid, $objId, $objType, $commentId)
    {
        clsRelateWiki::delRelateWiki($uid, $objId, $objType, $commentId, mObjRelateWiki::REL_OBJ_TYPE_COMMENT);
    }

    public static function getTopicRelated($topicId, $page, $uid = 0, $pageSize = 20)
    {
        $recommendWikiIds = [];
        $info = mTopicRelation::getByTopicId($topicId);
        if ($info && $info['show_wiki'] && $info['top_wikis']) {
            $recommendWikiIds = explode(',', $info['top_wikis']);
        }
        $response = cTopicWiki::getPagedList($topicId, $page, $pageSize);
        $isOver = $response['is_over'];
        $list = isset($response['list']) ? $response['list'] : [];
        $wikiIds = array_keys($list);
        $wikiIds = array_merge($recommendWikiIds, $wikiIds);
        $wikiIds = array_unique($wikiIds);
        $wikiList = sWiki::getWikiList($wikiIds, $uid);
        foreach ($wikiList as $wikiId => $row) {
            $wikiList[$wikiId]['statSign'] = basicStatSign::genStatSign(basicStatSign::MODULE_TOPIC_DETAIL_WIKI, [
                basicStatSign::EXTEND_KEY_OBJ_ID => $wikiId,
                basicStatSign::EXTEND_KEY_OBJ_TYPE => BlockType::TYPE_WIKI,
            ], ['topic_id' => $topicId, 'wiki_id' => $wikiId, 'basic_id' => $row['basic_id']]);
            if (in_array($row['id'], $recommendWikiIds)) {
                $wikiList[$wikiId]['is_recommend'] = 1;
            }
        }
        return ['list' => array_values($wikiList), 'is_over' => $isOver];
    }

    /**
     * 增加话题wiki
     * @param $noteId
     */
    public static function addTopicWiki($noteId)
    {
        $members = [];
        if ($noteId) {
            $list = mObjRelateWiki::getRelaWikiIdsByObjId($noteId);
            $lightTopicPhotos = $list ? ((new esPhotoService)->getLightTopicPhotos(['id' => $noteId], false)) : [];
            Log::info('add topic wiki', ['note_id' => $noteId, 'related_wiki' => $list ? true : false, 'light_topic_photo' => $lightTopicPhotos]);
            if ($list && $lightTopicPhotos && $lightTopicPhotos['light_topic'][$noteId]) {
                $tags = $lightTopicPhotos['light_topic'][$noteId];
                $tagsTitle = explode(' ', $tags);
                $topicArr = $tagsTitle ? TopicActivityModel::select(['id', 'title'], ['title' => $tagsTitle, 'status' => TopicActivityModel::STATUS_SUCCESS]) : [];
                $topicList = array_column($topicArr, null, 'id');
                $wikiIds = $list ? array_column($list, 'wiki_id') : [];
                $wikiList = mWiki::selectByWhere([
                    'id' => $wikiIds,
                    'status[!]' => mWiki::STATUS_DEL,
                    'is_default' => 1
                ], ['id', 'basic_id', "title"]);

                foreach ($topicList as $topicId => $topicInfo) {
                    //从redis获取分类
                    $rdsInfo = cTopicWiki::getCateNameById($topicId);
                    //redis不数据存在
                    if (!$rdsInfo && !is_array($rdsInfo)) {
                        $cateNames = TopicWiki::getCateNames($topicId, $topicInfo['title']);
                    } else {
                        //存在
                        $cateNames = $rdsInfo;
                    }
                    foreach ($wikiList as $row) {
                        $basicId = $row['basic_id'];
                        $wikiId = $row['id'];
                        $hot = GoodsHot::getGoodsHotById($basicId);
                        $hot = $hot ? $hot : 0;
//                        $start_hot = $hot;
//                        $str = '';
                        if ($cateNames) {
                            //遍历wiki是否存在这个标题
                            foreach ($cateNames as $cateName) {
                                if (strpos($row['title'], $cateName) !== false) {
                                    //获取商品品类热度
                                    $hot = $hot + 10000;
                                    Log::info("新增wiki加分记录", json_encode([
                                        "topic_id" => $topicId,
                                        "wiki_id" => $wikiId,
                                        "cate_name" => $cateNames
                                    ]));
//                                    $str = "-加分了-topic_id: " . $topicId;
                                    break;
                                }
                            }
                        }
//                        var_dump("开始热度:" . $start_hot . "---结束热度:" . $hot . $str);
                        $members[$wikiId] = $hot;
                    }
                    if ($members) {
                        cTopicWiki::addWikis($topicId, $members);
                    }
                    self::changeTopicWikiNum($topicId);
                }
            }
        }
    }

    public static function changeTopicWikiNum($topicId)
    {
        $wikNums = cTopicWiki::getWikisNum($topicId);
        $wikNums = $wikNums ? $wikNums : 0;
        TopicCounter::setWikisNumByTopicId($topicId, $wikNums);
    }


    /**
     * @desc 后台修改note根据id搜索wiki
     * @param $ids
     * @param $page
     * @param $size
     * @return array
     */
    public static function admListWikiByIds($ids, $page, $size)
    {
        $condition = [
            'id' => $ids,
            'status[!]' => mWiki::STATUS_DEL
        ];
        $count = mWiki::count($condition);

        $list = mWiki::selectByWhere([
            'AND' => $condition,
            'LIMIT' => [
                $size * ($page - 1),
                $size
            ]
        ]);
        $list = self::admFormatSearchList($list);
        $is_over = $page * $size >= $count ? 1 : 0;
        return compact('is_over', 'list', 'count');
    }

    /**
     * @desc 后台修改note根据关键词搜索wiki
     * @param $keyword
     * @param $page
     * @param $size
     * @return array
     */
    public static function admListWikiByKeyword($keyword, $page, $size)
    {
        $condition = [
            'title[~]' => $keyword,
            'status[!]' => mWiki::STATUS_DEL
        ];
        $count = mWiki::count($condition);

        $list = mWiki::selectByWhere([
            'AND' => $condition,
            'LIMIT' => [
                $size * ($page - 1),
                $size
            ]
        ]);
        $list = self::admFormatSearchList($list);
        $is_over = $page * $size >= $count ? 1 : 0;
        return compact('is_over', 'list', 'count');
    }

    public static function admFormatSearchList($list)
    {
        $response = [];
        if (!empty($list)) {
            foreach ($list as $v) {
                $response[] = [
                    'shop_info' => [
                        'name' => $v['channel_shop_name'],
                        'uid' => $v['channel_shop_id'],
                    ],
                    'title' => $v['title'],
                    'cover_img' => $v['cover_img'],
                    'id' => $v['id'],
                ];
            }
        }
        return $response;
    }

    /**
     * @desc 后台显示点图标签规则
     * @param $imgTag string
     * @param bool $format
     * @return string|array
     */
    public static function admFormatImgTags($imgTag, $format = true)
    {
        $tags = json_decode($imgTag, true);
        $temp = [];
        if (is_array($tags) && !empty($tags)) {
            $list = ShowTagFormat::formatList($tags);
            foreach ($list as $value) {
                $temp[] = $value['tag_name'];
            }

            if ($format) {
                $temp = array_map(function ($v) {
                    return '【 ' . $v . '】';
                }, $temp);
            }
        }
        return $format ? implode(" ", $temp) : $temp;
    }

    /**
     * @desc 后台获取note关联商品列表
     * @param $noteId
     * @return array
     * @throws \Exception
     */
    public static function admNoteRelateList($noteId)
    {
        $where = [
            'obj_id' => $noteId,
            'obj_type' => mObjRelateWiki::OBJ_TYPE_NOTE,
            'status' => mObjRelateWiki::STATUS_NORMAL
        ];
        $list = mObjRelateWiki::getByWhere($where);

        //按图片进行分组
        $response = [];
        if ($list) {
            $wikiArr = [];
            $goodsArr = [];
            foreach ($list as $v) {
                if ($v['wiki_id'] > 0) {
                    $wikiArr[$v['wiki_id']] = $v['wiki_id'];
                } else {
                    if ($v['goods_id'] > 0) {
                        $goodsArr[$v['goods_id']] = $v['goods_id'];
                    }
                }
            }
            //批量查询商品信息
            $goodsMap = empty($goodsArr) ? [] : Goods::Goods(array_values($goodsArr), Goods::FIELDS_GROUP_COMMUNITY);

            //批量查询wiki信息
            $wikiMap = empty($wikiArr) ? [] : AdmWiki::admWikiList(['id' => array_values($wikiArr)]);
            $wikiMap = $wikiMap['list'] ?? [];
            $wikiMap = empty($wikiMap) ? [] : array_column($wikiMap, null, 'id');
            $itemArr = [];
            foreach ($list as $v) {
                if ($v['wiki_id'] > 0 && isset($wikiMap[$v['wiki_id']])) {
                    $temp = $wikiMap[$v['wiki_id']];
                    $temp['rela_type'] = $v['type'];
                    $temp['wiki'] = 1;
                    $itemArr[$v['rel_obj_id']][] = $temp;
                } else {
                    if ($v['goods_id'] > 0 && isset($goodsMap[$v['goods_id']])) {
                        $temp = $goodsMap[$v['goods_id']];
                        $temp['rela_type'] = $v['type'];
                        $temp['wiki'] = 0;
                        $itemArr[$v['rel_obj_id']][] = $temp;
                    }
                }
            }

            foreach ($itemArr as $key => $item) {
                $response[$key] = [
                    'pic_id' => $key,
                    'list' => $item,
                ];
            }
        }

        return $response;
    }

    /**
     * @desc 后台note修改关联商品后更新缓存
     * @param $noteId
     * @return mixed
     */
    public static function admAfterSaveDelCache($noteId)
    {
        PhotoRelaBaseGoods::delItem($noteId);
        PhotoRelaGoods::delItem($noteId);

//        //查询关联
//        $has_recommend_goods = mObjRelateWiki::count([
//            'obj_id' => $noteId,
//            'obj_type' => mObjRelateWiki::OBJ_TYPE_NOTE,
//            'status' => mObjRelateWiki::STATUS_NORMAL,
//            'type' => mObjRelateWiki::TYPE_ARTIFICIAL
//        ]) > 0 ? 1 : 0; //后台推荐商品
//        Photos::updatePhotoById($noteId, ['has_recommend_goods' => $has_recommend_goods]);
        cPhotos::delete($noteId);

        //更新solr
        sPhotos::updatePhotoSolrAndCounter($noteId);
    }

    /**
     * @desc 后台note解除关联商品
     * @param $noteId
     * @param $adminId int 管理员id
     * @param $goodsId int goods id
     * @param $wikiId int wiki id
     * @param $type
     * @return bool
     */
    public static function admNoteRemoveRelate($noteId, $adminId, $goodsId, $wikiId, $type)
    {
        $where = [
            'obj_id' => $noteId,
            'obj_type' => mObjRelateWiki::OBJ_TYPE_NOTE,
            'rel_obj_type' => mObjRelateWiki::REL_OBJ_TYPE_PIC,
            'type' => $type,
        ];
        if ($goodsId > 0) {
            $where['goods_id'] = $goodsId;
        }
        if ($wikiId > 0) {
            $where['wiki_id'] = $wikiId;
        }
        $rs = mObjRelateWiki::updateData([
            'status' => mObjRelateWiki::STATUS_CLOSE,
            'edittime' => date('Y-m-d H:i:s'),
            'admin_uid' => $adminId,
        ], $where);

        return $rs;
    }

    /**
     * @desc 后台note关联商品
     * @param $noteId
     * @param $picId string 图片id
     * @param $adminId int 管理员id
     * @param $wikiId int wiki id
     * @return bool
     * @throws \Exception
     */
    public static function admNoteRelate($noteId, $picId, $adminId, $wikiId)
    {
        if (empty($wikiId)) {
            throw new \Exception('不存在的wiki');
        }
        $result = false;
        $checkUnique = self::admCheckNoteRelate($noteId, $picId, $wikiId);
        if ($checkUnique) {
            throw new \Exception('已关联商品');
        }
        $type = mObjRelateWiki::TYPE_ARTIFICIAL;
        $uid = IdParse::getUid($noteId);

        $where = [
            'obj_id' => $noteId,
            'obj_type' => mObjRelateWiki::OBJ_TYPE_NOTE,
            'rel_obj_id' => !empty($picId) ? $picId : '',
            'rel_obj_type' => !empty($picId) ? mObjRelateWiki::REL_OBJ_TYPE_PIC : 0,
            'wiki_id' => $wikiId
        ];
        $relateList = mObjRelateWiki::getByWhere($where);
        if ($relateList) {
            foreach ($relateList as $row) {
                if ($row['status'] != mObjRelateWiki::STATUS_NORMAL) {
                    $result = mObjRelateWiki::updateData([
                        'uid' => $uid,
                        'type' => $type,
                        'status' => mObjRelateWiki::STATUS_NORMAL,
                        'addtime' => date('Y-m-d H:i:s'),
                        'admin_uid' => $adminId,
                    ], $where);
                }
            }
        } else {
            $insertData = [
                'uid' => $uid,
                'obj_id' => $noteId,
                'obj_type' => mObjRelateWiki::OBJ_TYPE_NOTE,
                'rel_obj_id' => !empty($picId) ? $picId : '',
                'rel_obj_type' => !empty($picId) ? mObjRelateWiki::REL_OBJ_TYPE_PIC : 0,
                'wiki_id' => $wikiId,
                'admin_uid' => $adminId,
                'type' => $type,
                'addtime' => date('Y-m-d H:i:s'),
                'status' => mObjRelateWiki::STATUS_NORMAL,
            ];
            $result = mObjRelateWiki::insertData($insertData);
        }
        return $result;
    }

    /**
     *  获取wiki关联内容的最近时间
     */
    public static function getLastWikiRelateTime($wikiId)
    {
        $objRelateWikiParams = array(
            "wiki_id" => $wikiId,
            "status" => \Biz\model\wiki\ObjRelateWiki::STATUS_NORMAL,
            'ORDER' => ['addtime' => 'DESC']
        );

        $addtimeArr = \Biz\model\wiki\ObjRelateWiki::getByWhere($objRelateWikiParams, "addtime");
        return is_array($addtimeArr) && $addtimeArr ? (int)strtotime($addtimeArr[0]) : (int)0;
    }

    /**
     * @desc 后台验证note是否关联指定商品
     * @param $noteId
     * @param $picId
     * @param $wikiId
     * @return bool
     */
    public static function admCheckNoteRelate($noteId, $picId, $wikiId)
    {
        $commonCondition = [
            'obj_type' => mObjRelateWiki::OBJ_TYPE_NOTE,
            'obj_id' => $noteId,
            'rel_obj_type' => mObjRelateWiki::REL_OBJ_TYPE_PIC,
            'rel_obj_id' => $picId,
            'status' => mObjRelateWiki::STATUS_NORMAL,
        ];
        if ($wikiId > 0) {
            $commonCondition['wiki_id'] = $wikiId;
            return mObjRelateWiki::count($commonCondition);
        }
        return false;
    }

    /**
     * @desc 后台计算图片关联商品数量
     * @param $noteId
     * @return bool
     */
    public static function admGetGoodsCountByPhoto($noteId)
    {
        $condition = [
            'obj_id' => $noteId,
            'rel_obj_type' => mObjRelateWiki::REL_OBJ_TYPE_PIC,
            'status' => mObjRelateWiki::STATUS_NORMAL,
        ];
        return mObjRelateWiki::count($condition);
    }

    /**
     * 获取obj_id 通过wiki_id
     * @param $wiki_id
     * @param string $field
     * @return array|bool
     */
    public static function getObjIdByWikiId($wiki_id, $field = 'obj_id')
    {
        $where['obj_type'] = mObjRelateWiki::OBJ_TYPE_NOTE;
        $where['wiki_id'] = $wiki_id;
        $where['status'] = mObjRelateWiki::STATUS_NORMAL;
        $where['uid[!]'] = [11941, 6587838];
        return mObjRelateWiki::select($field, $where);
    }

    /**
     * 更新wiki详情页 住友说、 品牌说、 门店说、计数器
     * @param $wikiId
     * @param $basicId
     * @return bool
     */
    public static function syncWikiCommentCounter($wikiId, $basicId): bool
    {
        try {
            $user_comment_num = sWiki::getRelateObjNumByWikiId($wikiId, self::USER_COMMENT);//住友说
            $brand_comment_num = sWiki::getRelateObjNumByWikiId($wikiId, self::BRAND_COMMENT);//品牌说
            $store_comment_num = sWiki::getRelateObjNumByWikiId($wikiId, self::STORE_COMMENT);//门店说
            WikiBasicCounter::setCounter($basicId, WikiBasicCounter::BASIC_USER_COMMENT_NUM, $user_comment_num);
            WikiBasicCounter::setCounter($basicId, WikiBasicCounter::BASIC_BRAND_COMMENT_NUM, $brand_comment_num);
            WikiBasicCounter::setCounter($basicId, WikiBasicCounter::BASIC_STORE_COMMENT_NUM, $store_comment_num);

            return true;
        } catch (\Exception $exception) {
            Log::error('更新wiki详情页 住友说、 品牌说、 门店说、计数器',
                ['exception' => $exception, '$wikiId' => $wikiId, '$basicId' => $basicId]);

            return false;
        }
    }

    /**
     * 同步obj_relate_wiki 数据至es
     * @param $data
     * @return bool
     */
    public static function syncWikiCommentToEs($data)
    {
        $id = $data['id'] ?? 0;
        $objId = $data['obj_id'] ?? '';
        $wikiId = $data['wiki_id'] ?? '';
        $params = [];
        if ($id > 0 && $objId && $wikiId > 0) {

            $params['id'] = $id;
            $params['obj_id'] = $objId;
            $params['obj_type'] = $data['obj_type'];
            $params['rel_obj_id'] = $data['rel_obj_id'];
            $params['rel_obj_type'] = $data['rel_obj_type'];
            $params['wiki_id'] = $wikiId;
            $params['uid'] = $data['uid'];
            $params['type'] = $data['type'];
            $params['status'] = $data['status'];
            $params['admin_uid'] = $data['admin_uid'];

            $objInfoMap = MainContent::getBatchByIds([$objId]);
            $params['admin_score'] = $objInfoMap[$objId]['admin_score'] ?? 0;
            $params['addtime'] = $objInfoMap[$objId]['addtime'];

            $wikiInfoMap = Wiki::getWikiBaseInfos([$wikiId]);
            $params['basic_id'] = $wikiInfoMap[$wikiId]['basic_id'] ?? 0;

            EsObjRelateWikiSupplement::post($id, $params);

            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据内容id，同步修改es内的质量分数
     * @param $objId
     * @param $adminScore
     * @return bool
     */
    public static function syncAdminScoreToEs($objId, $adminScore): bool
    {
        if ($objId && $adminScore > 0) {
            $data ['query'] = ['term' => ['obj_id' => ['value' => $objId]]];
            $data ['script'] = ['source' => "ctx._source['admin_score'] = $adminScore"];
            $res = EsObjRelateWikiSupplement::editByQuery($data);
            if (!$res) {
                Log::error('syncAdminScoreToEs-更新失败', ['$data' => $data]);
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 根据内容id，同步修改es内的addtime
     * @param $objId
     * @param $addtime
     * @return bool
     */
    public static function syncAddtimeToEs($objId, $addtime): bool
    {
        if ($objId && $addtime > 0) {
            $data ['query'] = ['term' => ['obj_id' => ['value' => $objId]]];
            $data ['script'] = ['source' => "ctx._source['addtime'] = $addtime"];
            $res = EsObjRelateWikiSupplement::editByQuery($data);
            if (!$res) {
                Log::error('syncAddtimeToEs-更新失败', ['$data' => $data]);
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    public static function getType($objId)
    {
        $objType = 0;
        if (IdParse::getType($objId) == BlockType::TYPE_PHOTO || IdParse::getType($objId) == BlockType::TYPE_ANSWER) {
            $objType = mObjRelateWiki::OBJ_TYPE_NOTE;
        } else if (IdParse::getType($objId) == BlockType::TYPE_ARTICLE) {
            $objType = mObjRelateWiki::OBJ_TYPE_ARTICLE;
        } else if (IdParse::getType($objId) == BlockType::TYPE_BLANK) {
            $objType = mObjRelateWiki::OBJ_TYPE_BLANK;
        } else if (IdParse::getType($objId) == BlockType::TYPE_GUIDE) {
            $objType = mObjRelateWiki::OBJ_TYPE_GUIDE;
        }
        return $objType;
    }

    /**
     * 查询整屋及切note下关联的wiki信息
     *
     * @param $articleId
     * @param $noSearchId
     * @param $unique
     * @return array|bool
     */
    public static function getRelWikiForArticleList($articleId, $noSearchId = '', $unique = 0)
    {
        $objIds[] = $articleId;
        $noteIds = sArticle::getRelaNoteIds($articleId);//整屋下所有的note
        $objIds = array_merge($objIds, $noteIds);
        $where = [
            'obj_id' => $objIds,
            'obj_type' => [mObjRelateWiki::OBJ_TYPE_ARTICLE, mObjRelateWiki::OBJ_TYPE_NOTE],
            'status' => mObjRelateWiki::STATUS_NORMAL,
        ];
        if ($noSearchId) {
            $where['AND']['obj_id[!]'] = $noSearchId;
        }
        $result = mObjRelateWiki::getByWhere($where, 'wiki_id');
        if ($result) {
            return $unique ? $result : array_unique($result);
        }
        return [];
    }
}